package com.javatest.validate;


import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-11-10 上午9:21
 */
public class ValidationUtils {
    /**
     * 用于Java Bean校验的校验器
     * Obtain validator validator.
     *
     * @return the validator
     */
    public static Validator obtainValidator() {
        // 1、使用【默认配置】得到一个校验工厂  这个配置可以来自于provider、SPI提供
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        // 2、得到一个校验器
        return validatorFactory.getValidator();
    }

    /**
     * 用于方法校验的校验器
     * Obtain executable validator executable validator.
     *
     * @return the executable validator
     */
    public static ExecutableValidator obtainExecutableValidator() {
        return obtainValidator().forExecutables();
    }

    /**
     * Print violations.
     *
     * @param <T>        the type parameter
     * @param violations the violations
     */
    public static <T> void printViolations(Set<ConstraintViolation<T>> violations) {
        violations.stream().map(v -> v.getPropertyPath() + " " + v.getMessage() + ": " + v.getInvalidValue()).forEach(System.out::println);
    }

    /**
     * Obtain validator factory validator factory.
     *
     * @return the validator factory
     */
    public static ValidatorFactory obtainValidatorFactory() {
        return Validation.buildDefaultValidatorFactory();
    }
}
